package com.penngo.webspeed;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.penngo.webspeed.util.HttpRequester;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {
	private MyHandler handler;
//	private Map<String, String> urlMap;
//	private Map<String, Integer> idMap;
	private String[][] urls;
	private int urlLength = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		setContentView(R.layout.activity_main);
		setContentView(R.layout.active_main2);

		
		urls = new String[][]{
				{"淘宝", "http://m.taobao.com/", "21780"},  //21780
				{"百度", "http://m.baidu.com/", "38583"}, //38583
				{"有道词典", "http://m.youdao.com/", "17136"}, //17136
				{"360搜索", "http://m.so.com/s?mode=jisu", "7091"},//7091
				{"wikipedia", "http://en.m.wikipedia.org/", "20354"},//20354
				{"eBay", "http://m.ebay.com/", "13319"},//13319
				};
		urlLength = urls.length;
			R.id r = new R.id();
			Class<R.id> clazz = R.id.class;        
	        for(int i = 1; i <= urlLength; i++){
//	        	R.id.
	        	String tv = "tv" + i;
	        	String pb = "pb" + i;
	        	String speed = "speed" + i;
	        	try{
	        		Field tvField = clazz.getDeclaredField(tv);
	        		Field pbField = clazz.getDeclaredField(pb);
	        		Field speedField = clazz.getDeclaredField(speed);
	        		int tvid = tvField.getInt(r);
	        		int pbid = pbField.getInt(r);
	        		int speedid = speedField.getInt(r);
	        		
	        		TextView tView = (TextView)this.findViewById(tvid);
	        		tView.setText(urls[i -1][0]);
//	        		ProgressBar progressBar = (ProgressBar)findViewById(pbid);
//	        		TextView speedView = (TextView)findViewById(speedid);
	        		
	        	}
	        	catch(NoSuchFieldException e){
	    			e.printStackTrace();
	    			Log.e("1===========", "获取变量值出错====", e);
	    		}
	        	catch(IllegalAccessException e){
	        		e.printStackTrace();
	        		Log.e("2===========", "获取变量值出错====", e);
	        	}
	        }
		
        
		Button button = (Button) findViewById(R.id.button1);
		handler = new MyHandler();

		// 设置监听
		button.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				R.id r = new R.id();
				Class<R.id> clazz = R.id.class; 
				for(int i = 1; i <= urlLength; i++){
		        	String tv = "speed" + i;
		        	String pb = "pb" + i;
		        	try{
		        		Field tvField = clazz.getDeclaredField(tv);
		        		int tvid = tvField.getInt(r);
		        		TextView tView = (TextView)findViewById(tvid);
		        		tView.setText("正在检测..");
		        		
		        		Field pbField = clazz.getDeclaredField(pb);
		        		int pbid = pbField.getInt(r);
		        		ProgressBar progressBar = (ProgressBar)findViewById(pbid);
		        		progressBar.setProgress(0);
		        	}
		        	catch(NoSuchFieldException e){
		    			e.printStackTrace();
		    			Log.e("===========", "获取变量值出错====", e);
		    		}
		        	catch(IllegalAccessException e){
		        		e.printStackTrace();
		        		Log.e("===========", "获取变量值出错====", e);
		        	}
		        }
				new MyThread().start();
			}
		});
	}

	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			R.id r = new R.id();
			Class<R.id> clazz = R.id.class;        
        	String tv = "speed" + msg.what;
        	String pb = "pb" + msg.what;
        	try{
        		Field tvField = clazz.getDeclaredField(tv);
        		int tvid = tvField.getInt(r);
        		
        		Field pbField = clazz.getDeclaredField(pb);
        		int pbid = pbField.getInt(r);
        		
        		TextView tView = (TextView)findViewById(tvid);
        		tView.setText(msg.getData().getString("speed"));
        		
        		ProgressBar progressBar = (ProgressBar)findViewById(pbid);
        		progressBar.setProgress(msg.getData().getInt("speedbar"));
//        		
        	}
        	catch(Exception e){
        		e.printStackTrace();
        	}
		}
	}

	class MyThread extends Thread {
		@Override
		public void run() {
			for(int i = 1; i <= urlLength; i++){
				int id = i;
				String url = urls[i - 1][1];
				Log.e("============", id + " " + url);
	        	new TaskTread(id, url).start();
	        }
		}

	}

	class TaskTread extends Thread{
		private String url;
		private int id;
		public TaskTread(int id, String url){
			this.id = id;
			this.url = url;
		}
		public void run() {
			String speed = "访问失败";
			long time = 0;
			String result = "";
			try {
				long start = System.currentTimeMillis();
				int totallength = Integer.valueOf(urls[id -1][2]);
				HttpGet http = new HttpGet(url);
				http.addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 4.0.3; HTC One X Build/IML74K) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19");
		        HttpResponse response = new DefaultHttpClient().execute(http);
	            Header[] headers = response.getAllHeaders();
	            for (Header header : headers) {
//	                Log.e("headers==" + url, header.toString());
	            }
	            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
	                HttpEntity httpEntity = response.getEntity();
	                Log.e(url, "ContentLength=" + httpEntity.getContentLength());
//	                System.out.println("ContentLength=" + httpEntity.getContentLength());
//	                System.out.println("ContentEncoding=" + httpEntity.getContentEncoding());
//	                System.out.println("ContentType=" + httpEntity.getContentType());
	                BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
	                StringBuffer sb = new StringBuffer("");
	                String line = ""; //存储读取的一行内容
	                String NL = System.getProperty("line.separator");  //换行符
	                while ((line = in.readLine()) != null) {
	                    sb.append(line+NL);
//	                    sb.append(line);
	                    
	                    long end = System.currentTimeMillis();
	    				time = end - start;
	    				long len = sb.toString().getBytes().length;
	    				int speedbar = (int)len *100 / totallength;
	    				speedbar = speedbar < 90 ? speedbar : 90;
	    				speed = speed(time, len);
	                    Message message = new Message();
	        			Bundle bundle = new Bundle();
	        			bundle.putString("speed", speed);
	        			bundle.putInt("speedbar", speedbar);
	        			message.setData(bundle);
	        			message.what = id;//idMap.get(id);
	        			handler.sendMessage(message);
	        			Thread.sleep(500);
	                }
	                in.close();
	                result = sb.toString();
	                Log.e(url, "ContentLength=" + httpEntity.getContentLength() + "  resultLength=" + result.length());
	                if(url.indexOf("baidu") > 0){
	                	Log.e(url, result);
	                }
	            } else {
	                Log.e("======", "读取失败" + url + " " + response.getStatusLine().getStatusCode());
	            }
				
//				Document doc = Jsoup.connect(url).get();
//				result = doc.body().html();
//	            HttpRequester request = new HttpRequester();  
//	            HttpRequester.HttpRespons hr = request.sendGet(url);  
				long end = System.currentTimeMillis();
				time = end - start;

			} catch (Exception ex) {
				ex.printStackTrace();
			}
			if (result.length() > 0) {
				long len = result.getBytes().length;
				speed = speed(time, len);
			}
			Message message = new Message();
			Bundle bundle = new Bundle();
			bundle.putString("speed", speed);
			bundle.putInt("speedbar", 100);
			message.setData(bundle);
			message.what = id;//idMap.get(id);
			handler.sendMessage(message);
			
		}
	}
	
//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		getMenuInflater().inflate(R.menu.main, menu);
//		return true;
//	}

	private String speed(long time, long len) {
		String speed = "";
		if (time > 0) {
			long s = len * 1000 / time; // B/ms
			speed = s + "B/s";
			if (s > 1024) {
				s = s / 1024;
				speed = s + "KB/s";
			}
			if (s > 1024) {
				s = s / 1024;
				speed = s + "MB/s";
			}
			if (s > 1024) {
				s = s / 1024;
				speed = s + "GB/s";
			}
			String size = len + "B";
			if (len > 1024) {
				len = len / 1024;
				size = len + "KB";
			}
			if (len > 1024) {
				len = len / 1024;
				size = len + "MB";
			}
			String t = time + "ms";
			if (time > 1000) {
				time = time / 1000;
				t = time + "sec";

				if (time > 60) {
					time = time / 60;
					t = time + "min";
				}
			}
			speed = speed + "(" + size + ", " + t + ")";
		}
		return speed;
	}

}
